// 2013-9-11下午10:49:20  net.betou.trade.main.dao.role.impl.DaoImpl.java

package net.betou.trade.main.dao.role.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import net.betou.common.hibernate3.Finder;
import net.betou.common.hibernate3.HibernateBaseDao;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.entity.main.Role;
import net.betou.trade.main.dao.role.Dao;

/**
 * 
 * @author 叶装装
 */
@Repository
public class DaoImpl extends HibernateBaseDao< Role, Integer > implements Dao{

	public Role deleteById( Integer id ) {
		Role role = get( id );
//		int num = deleteRoleAdmin( role );//暂时先不删除创建的角色
//		log.debug("删除数："+String.valueOf(num));
		if( role != null ){
			getSession( ).delete( role );
		}
		return role;
	}
	
	@SuppressWarnings("unchecked")
	private int deleteRoleAdmin( Role role ){
		String hql = "select bean from AgentAndAdmins bean join bean.roles role where role.id=:roleId";
		Finder f = Finder.create(hql);
		f.setParam("roleId", role.getId());
		List<AgentAndAdmins> list = find(f, true);
		int num = 0;
		for(AgentAndAdmins aaa : list){
			aaa.getRoles().remove(role);
			num++;
		}
		return num;
	}

	public Role findById( Integer id ) {
		return get( id );
	}

	public Role save( Role bean ) {
		getSession( ).save( bean );
		return bean;
	}
	
	public Role findByManager( Boolean manager,  Integer id ){
		String hql = "from Role bean where bean.manager=? and bean.id=?";
		return ( Role ) findUnique( hql, manager, id );
	}
	
	@SuppressWarnings( "unchecked" )
	public List< Role > getListByIdentity( String identity ){
		Finder f = Finder.create( "from Role bean where bean.identity=:identity " );
		f.setParam( "identity", identity );
		return find( f, true );
	}
	
	public Integer maxLevel( Integer id ){
		
		String hql = "select max(level) from Role bean where bean.admin.id=:id";
		Query query = getSession( ).createQuery( hql );
		query.setParameter( "id", id );
		Object obj = query.iterate( ).next( ); 
		
		if( obj == null ){
			return 0;
		}
		
		return ( ( Number ) query.iterate( ).next( ) ).intValue( );
	}

	@Override
	protected Class< Role > getEntityClass( ) {
		return Role.class;
	}

}
